package com.magupe.im.web.db.utils;

import org.apache.commons.lang3.StringUtils;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ResultSetUtil {

    public static <T> List<T> resultToPojo(ResultSet resultSet, Class<T> clazz)
            throws SQLException, IllegalAccessException, InstantiationException, IntrospectionException, InvocationTargetException {
        ArrayList<T> list = new ArrayList<T>();
        while(resultSet.next()){
            T newInstance = clazz.newInstance();
            BeanInfo beanInfo = Introspector.getBeanInfo(newInstance.getClass());
            PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();

            // 获取列数
            int columnCount = resultSet.getMetaData().getColumnCount();
            for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
                // 获取属性名称
                String name = propertyDescriptor.getName();
                // 获取setter方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                for(int i = 1; i <= columnCount; i++){
                    String columnName = resultSet.getMetaData().getColumnName(i);
                    columnName= underLineToUpCase(columnName);
                    if(columnName.equals(name) && null != writeMethod){
                        // 对象属性赋值
                        writeMethod.invoke(newInstance, resultSet.getObject(resultSet.getMetaData().getColumnName(i)));
                    }
                }
            }
            list.add(newInstance);
        }
        return list;
    }

    /**
     * 下划线转驼峰
     *
     * @param str 需要为纯小写
     * @return
     */
    public static String underLineToUpCase(String str){
        str = StringUtils.lowerCase(str);
        String[] split = str.split("_");
        StringBuilder stringBuilder = new StringBuilder(split.length);
        if(split!=null&&split.length>0){
            stringBuilder.append(split[0]);
            for(int j=1;j<split.length;j++){
                stringBuilder.append(firstToUp(split[j]));
            }

        }
        str=stringBuilder.toString();
        return str;
    }

    /**
     * 首字母转大写
     *
     * @param str
     * @return
     */
    public static String firstToUp(String str){
        String replaceFirst = str.replaceFirst(str.substring(0,1), str.substring(0,1).toUpperCase());
        return replaceFirst;
    }
}
